package com.ftm.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ftm.dao.AdminDao;
import com.ftm.dao.impl.AdminDaoImpl;
import com.ftm.entity.Admin;
import com.ftm.entity.AjaxResponse;
import com.ftm.entity.Goods;
import com.ftm.entity.Shop;
import com.ftm.entity.User;
import com.ftm.service.AdminService;
import com.ftm.service.GoodsService;
import com.ftm.service.ShopService;
import com.ftm.service.UserService;
import com.ftm.service.impl.AdminServiceImpl;
import com.ftm.service.impl.GoodsServiceImpl;
import com.ftm.service.impl.ShopServiceImpl;
import com.ftm.service.impl.UserServiceImpl;
import com.ftm.tools.MD5Util;
import com.google.gson.Gson;

/**
 * Servlet implementation class BackstageServlet
 */
@WebServlet("/BackstageServlet")
public class BackstageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	// Dao对象
	AdminDao adminDao = new AdminDaoImpl();
	AdminService adminService = new AdminServiceImpl();
	MD5Util md5 = new MD5Util();
	UserService userService = new UserServiceImpl();
	ShopService shopService = new ShopServiceImpl();
	GoodsService goodsService = new GoodsServiceImpl();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public BackstageServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置请求编码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		// 获取当前登入用户
		String adminuser = "";
		if (request.getParameter("adminuser") != null) {
			adminuser = request.getParameter("adminuser");
		}
		System.out.println("adminuser:" + adminuser);
		// 标记当前为何种操作的变量
		String op = "";
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}
		// 获取修改的密码
		String pwd0 = request.getParameter("pwd0");
		String pwd1 = request.getParameter("pwd1");
		String pwd2 = request.getParameter("pwd2");
		if (pwd0 != null || pwd1 != null || pwd2 != null) {
			op = "updatepwd";
		}
		System.out.println("op:" + op);
		// 查询所有管理员信息
		if ("queryalladmin".equals(op)) {
			doqueryalladmin(request, response);
		}
		// 增加管理员
		else if ("addadmin".equals(op)) {
			doaddadmin(request, response);
		}
		// 重复提交
		else if ("ajaxadminname".equals(op)) {
			doajaxadmin(request, response);
		}
		// 删除管理员
		else if ("deladmin".equals(op)) {
			dodeladmin(request, response, adminuser);
		}
		// 查询个人信息
		else if ("querypersonal".equals(op)) {
			doquerypersonal(request, response, adminuser);
		}
		// 修改密码
		else if ("updatepwd".equals(op)) {
			doupdatepwd(response, adminuser, pwd0, pwd1, pwd2);
		}
		// 查询所有用户
		else if ("queryalluser".equals(op)) {
			doqueryalluser(request, response);
		}
		// 设置用户权限
		else if ("setstate".equals(op)) {
			dosetstate(request, response);
		}
		// 查询所有店铺
		else if ("queryallshop".equals(op)) {
			doqueryallshop(request, response);
		}
		// 设置店铺权限
		else if ("setshopstate".equals(op)) {
			dosetshopstate(request, response);
		}
		// 查询所有商品
		else if ("queryallgoods".equals(op)) {
			doqueryallgoods(request, response);
		}
		// 设置商品权限
		else if ("setgoodsstate".equals(op)) {
			dosetgoodsstate(request, response);
		}
	}

	private void dodeladmin(HttpServletRequest request, HttpServletResponse response, String adminuser)
			throws IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		// 先获取请求参数的值
		String adminname = "";
		if (request.getParameter("adminname") != null) {
			adminname = request.getParameter("adminname");
		}
		// 设置res的值
		AjaxResponse res = new AjaxResponse(false + "", 200);
		// 如果是超级管理员才有权限删除
		if ("superadmin".equals(adminuser)) {
			// 2 调用 service的方法判断删除是否成功
			boolean flag = adminDao.delAdmin(adminname);
			res = new AjaxResponse(flag + "", 200);
		}
		// 3将list转换为json格式的字符串
		Gson gson = new Gson();
		String jsonString = gson.toJson(res);
		// 4 响应
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsonString);
		// 5.关闭
		outPrintWriter.close();
	}

	private void dosetgoodsstate(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		// 2.state=1表示允许使用
		int ustate = Integer.parseInt(request.getParameter("ustate"));
		System.out.println("ustate:" + ustate);
		int goodsid = Integer.parseInt(request.getParameter("goodsid"));
		boolean f = goodsService.setGoodsState(goodsid, ustate);
		System.out.println("f=================" + f);
		AjaxResponse res = new AjaxResponse(f + "", 200);
		// 3将list转换为json格式的字符串
		Gson gson = new Gson();
		String jsonString = gson.toJson(res);
		// 4 响应
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsonString);
		// 5.关闭
		outPrintWriter.close();
	}

	private void doqueryallgoods(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<Goods> list = goodsService.queryAllGoods();
		request.setAttribute("list", list);
		request.getRequestDispatcher("GoodsList.jsp").forward(request, response);
	}

	private void dosetshopstate(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		// 2.state=1表示允许使用
		int ustate = Integer.parseInt(request.getParameter("ustate"));
		System.out.println("ustate:" + ustate);
		String shopname = request.getParameter("shopname");
		boolean f = shopService.setShopState(shopname, ustate);
		AjaxResponse res = new AjaxResponse(f + "", 200);
		// 3将list转换为json格式的字符串
		Gson gson = new Gson();
		String jsonString = gson.toJson(res);
		// 4 响应
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsonString);
		// 5.关闭
		outPrintWriter.close();
	}

	private void doqueryallshop(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<Shop> list = shopService.QueryAllShop();
		request.setAttribute("list", list);
		request.getRequestDispatcher("ShopList.jsp").forward(request, response);
	}

	private void dosetstate(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		// 2.state=1表示允许使用
		int ustate = Integer.parseInt(request.getParameter("ustate"));
		System.out.println("ustate:" + ustate);
		String username = request.getParameter("username");
		boolean f = userService.setUserState(username, ustate);
		AjaxResponse res = new AjaxResponse(f + "", 200);
		// 3将list转换为json格式的字符串
		Gson gson = new Gson();
		String jsonString = gson.toJson(res);
		// 4 响应
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsonString);
		// 5.关闭
		outPrintWriter.close();
	}

	private void doqueryalluser(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<User> list = userService.getUser();
		request.setAttribute("list", list);
		request.getRequestDispatcher("UserList.jsp").forward(request, response);
	}

	private void doupdatepwd(HttpServletResponse response, String adminuser, String pwd0, String pwd1, String pwd2)
			throws IOException {
		// 判断初始密码是否正确
		// 加密
		String md5pwd = md5.getEncodeByMd5(pwd0);
		boolean f = adminService.DetermineAdmin(adminuser, md5pwd);
		if (f) {
			// 判断两次密码是否一致
			if (pwd1.equals(pwd2)) {
				// 加密
				String md5pw1 = md5.getEncodeByMd5(pwd1);
				// 修改密码
				boolean f1 = adminService.UpdateAdminpwd(adminuser, md5pw1);
				if (f1) {
					response.getWriter().append(
							"<script>alert('修改密码成功！');location.href='http://localhost:8080/ForTheMorning/BackstageServlet?op=querypersonal'</script>");
				} else {
					response.getWriter().append(
							"<script>alert('修改密码失败!');location.href='http://localhost:8080/ForTheMorning/BackstageServlet?op=querypersonal'</script>");
				}
			} else {
				// 提示错误
				response.getWriter().append(
						"<script>alert('两次修改密码不一致！请重试!');location.href='http://localhost:8080/ForTheMorning/BackstageServlet?op=querypersonal'</script>");
			}
		} else {
			// 提示错误
			response.getWriter().append(
					"<script>alert('原密码输入错误!');location.href='http://localhost:8080/ForTheMorning/BackstageServlet?op=querypersonal'</script>");
		}
	}

	private void doquerypersonal(HttpServletRequest request, HttpServletResponse response, String adminuser)
			throws ServletException, IOException {
		Admin admin = adminService.queryoneAdmin(adminuser);
		System.out.println("查找到的管理员的信息：" + admin);
		// 转发给页面
		request.setAttribute("admin", admin);
		request.getRequestDispatcher("Personal.jsp").forward(request, response);
	}

	private void doajaxadmin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		String adminuser = request.getParameter("adminuser");
		System.out.println("adminuser :" + adminuser);
		// 2 调用 service的方法,查询是否存在typename对象
		Admin admin = adminDao.getAdminByName(adminuser);
		String msg = "用户名已存在，请换一个！";
		if (admin == null) {
			// ?没有找到
			msg = "用户名不存在,可以使用！";
		}

		// 3将list转换为json格式的字符串
		Gson gson = new Gson();
		String jsonString = gson.toJson(msg);

		// 4 响应
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsonString);

		// 5.关闭
		outPrintWriter.close();
	}

	private void doaddadmin(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		String adminuser = request.getParameter("adminuser");
		System.out.println("adminuser:" + adminuser);
		String adminpwd = request.getParameter("adminpw");
		String adminpwd2 = request.getParameter("adminpw2");
		String adminname = request.getParameter("adminname");
		// 超级管理员判断，只有超级管理员有权限增加删除管理员
		if ("superadmin".equals(adminuser)) {
			// 非空判断
			if ("".equals(adminuser) || "".equals(adminpwd) || "".equals(adminpwd2) || "".equals(adminname)) {
				response.getWriter().append(
						"<script>alert('用户名密码姓名不能为空!');location.href='http://localhost:8080/ForTheMorning/adminadd.jsp'</script>");
			} else {
				// 判断两次密码是否相同
				if (adminpwd.equals(adminpwd2)) {
					Admin admin = new Admin(adminuser, adminpwd, adminname);
					System.out.println(admin);
					boolean flag = adminDao.addAdmin(admin);
					System.out.println(flag);
					if (flag) {
						// 转发到显示servelt上进行查询，直接调用doQuery的方法即可。
						response.getWriter().append(
								"<script>alert('添加成功!');location.href='http://localhost:8080/ForTheMorning/BackstageServlet?op=queryalladmin'</script>");
					} else {
						// 转发到回到newstype增加的页面
						// 失败分两种情况，一种是如果名字重复；另外可能发生异常
						request.setAttribute("msg", "增加失败！请重新添加。");
						request.getRequestDispatcher("adminadd.jsp").forward(request, response);

					}
				} else {
					request.setAttribute("msg", "两次密码不一致，增加失败！");
					request.getRequestDispatcher("adminadd.jsp").forward(request, response);
				}
			}
		} else {
			response.getWriter().append(
					"<script>alert('你没有权限这么做！');location.href='http://localhost:8080/ForTheMorning/BackstageServlet?op=queryalladmin'</script>");
		}
	}

	private void doqueryalladmin(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<Admin> list = adminDao.getAdmin("");
		request.setAttribute("list", list);
		request.getRequestDispatcher("index.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
